package com.spcloud.demo.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.net.InetAddress;

/**
 * <p>TODO</p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author cuiyh9
 * @version 1.0
 * @Date Created in 2019年09月24日 15:48
 * @since 1.0
 */
public class MyMqttClient {

    private MqttClient mqttClient;

    public MyMqttClient() throws Exception {

        mqttClient = new MqttClient(MyMqttInfo.host, MyMqttInfo.clientId, new MemoryPersistence());

    }

    public void connect() throws Exception {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(MyMqttInfo.userName);
        options.setPassword(MyMqttInfo.password.toCharArray());
        options.setKeepAliveInterval(10);
        options.setConnectionTimeout(10);
        options.setAutomaticReconnect(true);
        options.setSocketFactory(SslUtils.getSocketFactory());
        try {
            if (!mqttClient.isConnected()) {
                mqttClient.connect();
                mqttClient.setCallback(new MyMqttClientCallBack());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MqttTopic getMqttTopic(String topic) throws Exception {
        if (!mqttClient.isConnected()) {
            connect();
        }

        if (mqttClient.isConnected()) {
            return mqttClient.getTopic(topic);
        } else {
            throw new Exception();
        }

    }

    public void publish(MqttTopic topic, MqttMessage message) throws MqttException {
        MqttDeliveryToken deliveryToken = topic.publish(message);
        deliveryToken.waitForCompletion();
        System.out.println("topic 发送消息");
    }


    public static void main(String[] args) throws Exception {

        InetAddress addr = InetAddress.getLocalHost();

        System.out.println("============start=========ip:" + addr.getHostAddress());
        MyMqttClient myMqttClient = new MyMqttClient();
        myMqttClient.connect();
        MqttTopic topic = myMqttClient.getMqttTopic(MyMqttInfo.topic);
        MqttMessage message = new MqttMessage();
        myMqttClient.publish(topic, message);
        System.out.println("topic:" + message.isRetained() + "============");

    }

}